import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const upload = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
      const isH5 = typeof window !== 'undefined' && typeof document !== 'undefined'
      // H5 且传入了 File/Blob：使用 fetch + FormData 以更好兼容浏览器端 Blob 上传
      if (isH5 && config.file) {
        try {
          const headers = config.header || {}
          const form = new FormData()
          const fieldName = config.name || 'file'
          const filename = (config.file && (config.file.name || `upload_${Date.now()}`)) || `upload_${Date.now()}`
          form.append(fieldName, config.file, filename)
          if (config.formData) {
            Object.keys(config.formData).forEach(k => form.append(k, config.formData[k]))
          }
          fetch(baseUrl + config.url, {
            method: 'POST',
            headers, // 不要显式设置 Content-Type，浏览器会自动带上 multipart 边界
            body: form
          }).then(async (res) => {
            let text = await res.text()
            let result
            try { result = JSON.parse(text) } catch (e) { result = { code: res.status, msg: text } }
            const code = result.code || res.status || 200
            const msg = errorCode[code] || result.msg || errorCode['default']
            if (code === 200) {
              resolve(result)
            } else if (code == 401) {
              showConfirm("登录状态已过期，您可以继续留在该页面，或者重新登录?").then(res2 => {
                if (res2.confirm) {
                  store.dispatch('LogOut').then(() => {
                    uni.reLaunch({ url: '/pages/login/login' })
                  })
                }
              })
              reject('无效的会话，或者会话已过期，请重新登录。')
            } else if (code === 500) {
              toast(msg)
              reject('500')
            } else {
              toast(msg)
              reject(code)
            }
          }).catch((error) => {
            let { message } = error || {}
            if (message == 'Network Error') {
              message = '后端接口连接异常'
            } else if (message && message.includes && message.includes('timeout')) {
              message = '系统接口请求超时'
            } else if (message && message.includes && message.includes('Request failed with status code')) {
              message = '系统接口' + message.substr(message.length - 3) + '异常'
            }
            toast(message || '上传失败')
            reject(error)
          })
        } catch (e) {
          toast('上传失败')
          reject(e)
        }
        return
      }

      // 其他端或走文件路径上传：使用 uni.uploadFile
      uni.uploadFile({
        timeout: config.timeout || timeout,
        url: baseUrl + config.url,
        // H5 可传入 File/Blob 对象；原生/小程序使用 filePath
        file: config.file,
        filePath: config.filePath,
        name: config.name || 'file',
        header: config.header,
        formData: config.formData,
        success: (res) => {
          let result = JSON.parse(res.data)
          const code = result.code || 200
          const msg = errorCode[code] || result.msg || errorCode['default']
          if (code === 200) {
            resolve(result)
          } else if (code == 401) {
            showConfirm("登录状态已过期，您可以继续留在该页面，或者重新登录?").then(res2 => {
              if (res2.confirm) {
                store.dispatch('LogOut').then(() => {
                  uni.reLaunch({ url: '/pages/login/login' })
                })
              }
            })
            reject('无效的会话，或者会话已过期，请重新登录。')
          } else if (code === 500) {
            toast(msg)
            reject('500')
          } else if (code !== 200) {
            toast(msg)
            reject(code)
          }
        },
        fail: (error) => {
          let { message } = error
          if (message == 'Network Error') {
            message = '后端接口连接异常'
          } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
          } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
          }
          toast(message)
          reject(error)
        }
      })
  })
}

export default upload
